A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
It only contains lowercase letters, hyphens, and/or punctuation (no digits).
There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".
Given a string sentence, return the number of valid words in sentence.
一樣先把題目看不懂的部分拿去翻譯
第二段的判別部分雖然繁瑣但比較簡單,所以先產出來了
public boolean isValid(String token ){
if (token.isEmpty()){
return false;
}
int hCount = 0;
int pCount = 0;
for (int i = 0; i<token.length();i++){
char c = token.charAt(i);
if (Character.isDigit(c)){
return false;
}else if (c == '-'){
hCount ++;
if (hCount > 1 || i == 0 || i== token.length()-1
|| !Character.isLowerCase(token.charAt(i-1))
|| !Character.isLowerCase(token.charAt(i+1)) ){
return false;
}
}else if (c =='!' || c =='.' || c ==','){
pCount ++;
if (pCount > 1 || i != token.length()-1){
return false;
}
}else if (!Character.isLowerCase(c)){
return false;
}
}
return true;
不過我想很久都寫不出第一步,感覺沒有學過能夠拆解字串的語法,所以最終上網搜尋了一下...
然後出現了一個我從來沒聽過的詞----「正則表達式」!
所以第一段程式就長這樣
public int countValidWords(String sentence){
//依照空格拆解出單字
//trim可刪除頭尾空白
//正則表達式\s+可匹配任意數量空格
int count = 0;
String[] wd = sentence.trim().split("\s+");
for (String token : wd){
if (isValid(token)){
count++;
}
}
return count;
}
丟去leetcode看結果!很愉快的成功下課!
但由於今天是中秋節,所以先不精修程式了,嫦娥會原諒我的:P